<?php

namespace App\Models\Sgdzz;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Issue extends Model
{
    protected $table = 'game_sgdzz_issue';
    
    const 
    
        TYPE_PINEAPPLE = 1,     //菠萝
        TYPE_BANANA    = 2,     //香蕉
        TYPE_APPLE     = 3,     //苹果
    
        STATUS_RUNNING = 0,     //进行中
        STATUS_OPENING = 1,     //开奖中
        STATUS_FINISHED = 2;    //已开奖

    public static function getRunningIssue() {
        $info = self::where('status', self::STATUS_RUNNING)->orderBy('id', 'DESC')->first();
        
        if(empty($info)) {
            $info = new \stdClass();
            $info->id = 0;
            $info->end_at = date('Y-m-d H:i:s');
        }

        return [
            'id' => (int)$info->id,
            'openAfter' => strtotime($info->end_at) - time(),       // 小于等于说明开奖中
        ];
    }

    /**
     * 获取开奖结果（类型）
     */
    public static function getIssueWinType($issue) {
        $info = self::where('id', $issue)->first();
        
        if(empty($info->id)) {
            return -1;
        }
        
        if($info->status == self::STATUS_RUNNING) {
            return 0;
        }
        
        if($info->status == self::STATUS_OPENING) {
            return -2;
        }
        
        return $info->win_type;
    }
    
    /**
     * 开启下一期
     */
    public static function createNextIssue() {
        $currentIssue = self::getRunningIssue();
        if( !empty($currentIssue['id']) && ($currentIssue['openAfter'] > 0) ) { //存在进行中期号，返回失败
            return false;
        }
        $endTime = config('sgdzz.time_per_issue') + config('sgdzz.issue_opening_time');
        $issueModel = new Issue();
        $issueModel->end_at = (Carbon::now()->addSeconds($endTime));
        $issueModel->save();
        
        return $issueModel->id;
    }
    
    /**
     * 获取最近几期中奖信息（期号、中奖类型）
     */
    public static function getLatestWinInfo($size = 30) {
        if(empty($size)) {
            $size = 30;
        }
        $list = self::where('status', self::STATUS_FINISHED)
            ->select('id', 'win_type as winType')
            ->orderBy('id', 'DESC')
            ->take($size)
            ->get()
            ->toArray();
        
        return $list;
    }
}
